<template>
  <div class="orders-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单"
        style="width: 200px"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select 
        v-model="statusFilter" 
        placeholder="订单状态"
        style="width: 120px; margin-left: 16px"
        @change="handleSearch"
      >
        <el-option label="全部" value="" />
        <el-option label="待处理" value="pending" />
        <el-option label="处理中" value="processing" />
        <el-option label="已完成" value="completed" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
    </div>

    <!-- 订单列表 -->
    <el-table :data="orders" style="width: 100%" v-loading="loading">
      <el-table-column prop="ID" label="订单号" width="100" />
      <el-table-column prop="CreatedAt" label="下单时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.CreatedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="OrderType" label="订单类型" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.OrderType === '堂食' ? 'success' : 'warning'" size="small">
            {{ scope.row.OrderType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="TotalAmount" label="总金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.TotalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="Status" label="订单状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.Status)" size="small">
            {{ getStatusText(scope.row.Status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="PaymentStatus" label="支付状态" width="100">
        <template #default="scope">
          <el-tag :type="getPaymentStatusType(scope.row.PaymentStatus)" size="small">
            {{ getPaymentStatusText(scope.row.PaymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link
            @click="showOrderDetail(row)"
          >
            查看详情
          </el-button>
          <el-button
            type="success"
            link
            v-if="row.Status === 'pending'"
            @click="updateOrderStatus(row.ID, 'processing')"
          >
            接单
          </el-button>
          <el-button
            type="info"
            link
            v-if="row.Status === 'processing'"
            @click="updateOrderStatus(row.ID, 'completed')"
          >
            完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="订单详情"
      width="700px"
      class="order-detail-dialog"
      :before-close="handleClose"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-header">
          <div class="status-banner" :class="currentOrder.Status">
            <span class="status-text">{{ getStatusText(currentOrder.Status) }}</span>
          </div>
          <div class="order-info">
            <!-- 基本信息 -->
            <div class="info-row">
              <div class="info-item">
                <span class="label">订单号：</span>
                <span class="value">{{ currentOrder.ID }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间：</span>
                <span class="value">{{ formatDate(currentOrder.CreatedAt) }}</span>
              </div>
            </div>

            <!-- 用户信息 -->
            <div class="info-row">
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ currentOrder.User?.Username }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户ID：</span>
                <span class="value">{{ currentOrder.UserID }}</span>
              </div>
            </div>

            <!-- 订单类型和支付状态 -->
            <div class="info-row">
              <div class="info-item">
                <span class="label">就餐方式：</span>
                <el-tag 
                  :type="currentOrder.OrderType === 'dine_in' ? 'success' : 'warning'"
                  effect="plain"
                >
                  {{ currentOrder.OrderType === 'dine_in' ? '堂食' : '外卖' }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">支付状态：</span>
                <el-tag 
                  :type="getPaymentStatusType(currentOrder.PaymentStatus)"
                  effect="plain"
                >
                  {{ getPaymentStatusText(currentOrder.PaymentStatus) }}
                </el-tag>
              </div>
            </div>

            <!-- 外卖信息 -->
            <template v-if="currentOrder.OrderType === 'takeout'">
              <div class="info-row">
                <div class="info-item full-width">
                  <span class="label">配送地址：</span>
                  <span class="value">{{ currentOrder.Address }}</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ currentOrder.Phone || currentOrder.User?.Phone }}</span>
                </div>
                <div class="info-item">
                  <span class="label">用户邮箱：</span>
                  <span class="value">{{ currentOrder.User?.Email }}</span>
                </div>
              </div>
            </template>
          </div>
        </div>

        <el-divider>订单明细</el-divider>

        <el-table :data="currentOrder.Items" border class="detail-table">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="dish-info">
                <img :src="row.Dish?.image_url || '/default-dish.jpg'" class="dish-image">
                <div class="dish-detail">
                  <span class="dish-name">{{ row.Dish?.name }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="Price" label="单价" width="120" align="center">
            <template #default="{ row }">
              ¥{{ row.Price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="Quantity" label="数量" width="100" align="center" />
          <el-table-column prop="Subtotal" label="小计" width="120" align="right">
            <template #default="{ row }">
              ¥{{ row.Subtotal.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-total">
          <span>订单总额：</span>
          <span class="total-amount">¥{{ currentOrder.TotalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

// 定义与后端对应的接口
interface User {
  ID: number
  Username: string
  Phone: string
  Email: string
}

interface OrderItem {
  ID: number
  OrderID: number
  DishID: number
  Quantity: number
  Price: number
  Subtotal: number
  CreatedAt: string
  UpdatedAt: string
}

interface Order {
  ID: number
  UserID: number
  User: User
  TotalAmount: number
  Status: string
  OrderType: string
  Address: string
  Phone: string
  Items: OrderItem[]
  PaymentStatus: string
  PaymentMethod: string
  CreatedAt: string
  UpdatedAt: string
}

const store = useStore()
const router = useRouter()
const loading = ref(false)
const orders = ref<Order[]>([])
const dialogVisible = ref<boolean>(false)
const currentOrder = ref<Order | null>(null)
const searchQuery = ref('')
const statusFilter = ref('')

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 修改加载订单的函数
const loadOrders = async () => {
  loading.value = true
  try {
    const response = await fetch(
      `http://localhost:8080/api/admin/orders?page=${currentPage.value}&pageSize=${pageSize.value}`,
      {
        headers: {
          'Authorization': `Bearer ${store.state.token}`
        }
      }
    )
    const data = await response.json()
    if (response.ok) {
      orders.value = data.orders
      total.value = data.total
    }
  } catch (error) {
    console.error('Load orders error:', error)
    ElMessage.error('加载订单失败')
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const showOrderDetail = async (order: Order) => {
  try {
    console.log('Opening dialog for order:', order.ID)  // 添加调试日志
    currentOrder.value = order
    console.log('Current order:', currentOrder.value)  // 添加调试日志
    dialogVisible.value = true  // 设置为 true 来打开对话框
  } catch (error) {
    console.error('Error showing order detail:', error)
    ElMessage.error('打开订单详情失败')
  }
}

// 更新订单状态
const updateOrderStatus = async (orderId: number, status: string) => {
  try {
    const response = await fetch(`http://localhost:8080/api/admin/orders/${orderId}/status`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ status })
    })
    
    if (response.ok) {
      ElMessage.success('更新订单状态成功')
      loadOrders() // 重新加载订单列表
    } else {
      const error = await response.json()
      throw new Error(error.error || '更新订单状态失败')
    }
  } catch (error) {
    console.error('Update order status error:', error)
    ElMessage.error(error.message || '更新订单状态失败')
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'cancelled': 'info'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取支付状态类型
const getPaymentStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'unpaid': 'danger',
    'paid': 'success',
    'refunded': 'info'
  }
  return statusMap[status] || ''
}

// 获取支付状态文本
const getPaymentStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'unpaid': '未支付',
    'paid': '已支付',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 处理搜索
const handleSearch = () => {
  // 实现搜索逻辑
  loadOrders()
}

// 添加关闭对话框的处理函数
const handleClose = () => {
  dialogVisible.value = false
  currentOrder.value = null
}

// 在 script setup 中添加 formatDate 函数
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadOrders()
}

// 处理每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  loadOrders()
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.order-details {
  padding: 20px;
}

.order-info {
  margin-bottom: 24px;
}

.order-info h3,
.order-items h3 {
  margin-bottom: 16px;
  font-weight: 500;
}

.order-info p {
  margin: 8px 0;
  color: #666;
}

.order-items {
  margin-top: 24px;
}

.order-total {
  margin-top: 16px;
  text-align: right;
  font-weight: bold;
}

/* 添加一些新的样式 */
.order-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.status-banner {
  padding: 20px;
  color: #fff;
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
}

.status-banner.completed {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
}

.status-banner.cancelled {
  background: linear-gradient(135deg, #909399 0%, #82848a 100%);
}

.status-text {
  font-size: 18px;
  font-weight: 500;
}

.info-row {
  display: flex;
  margin: 15px 20px;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.info-item.full-width {
  flex: 2;
}

.label {
  color: #909399;
  margin-right: 10px;
  min-width: 70px;
}

.value {
  color: #303133;
}

.dish-info {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.dish-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.dish-name {
  font-size: 14px;
  color: #303133;
}

.order-total {
  text-align: right;
  padding: 20px;
  background-color: #f7f8fa;
  border-top: 1px solid #ebeef5;
}

.total-amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 